<template>
  <div class="chat-layout">
    <!-- 侧边悬浮栏 -->
    <div class="floating-sidebar">
      <v-btn
        class="sidebar-btn"
        icon="mdi-plus"
        variant="text"
        size="large"
        color="primary"
        @click="newChat"
        :title="'新建对话'"
      >
      </v-btn>
      <v-btn
        class="sidebar-btn"
        icon="mdi-history"
        variant="text"
        size="large"
        color="primary"
        @click="showHistory = true"
        :title="'历史记录'"
      >
      </v-btn>
    </div>

    <!-- 历史记录弹出层 -->
    <v-dialog v-model="showHistory" fullscreen transition="dialog-bottom-transition">
      <v-card class="history-dialog">
        <v-toolbar dark color="primary" class="history-toolbar">
          <v-btn icon="mdi-close" variant="text" @click="showHistory = false"></v-btn>
          <v-toolbar-title class="history-title">
            <v-icon size="24" class="mr-2">mdi-history</v-icon>
            历史对话记录
          </v-toolbar-title>
          <v-spacer></v-spacer>
          <div class="history-count">共 {{ chatHistory.length }} 条记录</div>
        </v-toolbar>
        
        <div class="history-content">
          <v-container>
            <v-row>
              <v-col cols="12" md="8" offset-md="2">
                <div class="history-list">
                  <v-card
                    v-for="(chat, index) in chatHistory"
                    :key="index"
                    class="history-item mb-4"
                    elevation="2"
                    @click="loadChat(chat)"
                  >
                    <div class="history-item-content">
                      <div class="history-item-header">
                        <div class="history-item-date">
                          <v-icon size="20" class="mr-2">mdi-calendar</v-icon>
                          {{ formatDate(chat.date) }}
                        </div>
                        <v-chip
                          size="small"
                          color="primary"
                          variant="outlined"
                          class="history-item-count"
                        >
                          {{ chat.messages.length }} 条对话
                        </v-chip>
                      </div>
                      <div class="history-item-preview">
                        {{ chat.messages[0]?.text.slice(0, 100) }}...
                      </div>
                      <div class="history-item-footer">
                        <v-btn
                          variant="text"
                          color="primary"
                          size="small"
                          class="history-item-btn"
                        >
                          <v-icon size="16" class="mr-1">mdi-reload</v-icon>
                          恢复对话
                        </v-btn>
                      </div>
                    </div>
                  </v-card>
                </div>
              </v-col>
            </v-row>
          </v-container>
        </div>
      </v-card>
    </v-dialog>

    <div class="chat-main">
      <div class="chat-content">
        <div class="welcome-message" v-if="messages.length === 0">
          <v-icon size="64" color="primary" class="mb-4">mdi-robot</v-icon>
          <h2 class="text-h5 mb-4">欢迎使用 AI 助手</h2>
          <p class="text-body-1 mb-6">我可以帮你回答问题、编写代码、解决问题等。试着问我一些问题吧！</p>
          
          <div class="suggestions">
            <template v-if="loadingSuggestions">
              <v-progress-circular
                indeterminate
                color="primary"
                size="24"
              ></v-progress-circular>
              <span class="ml-2">正在思考问题建议...</span>
            </template>
            <template v-else>
              <v-chip
                v-for="(suggestion, index) in suggestions"
                :key="index"
                class="ma-2 suggestion-chip"
                variant="outlined"
                :color="chipColors[index % chipColors.length]"
                :loading="refreshingSuggestion === index"
                @click="handleSuggestionClick(suggestion)"
              >
                {{ suggestion }}
                <template v-slot:append>
                  <v-icon size="small" @click.stop="refreshSuggestion(index)">
                    mdi-refresh
                  </v-icon>
                </template>
              </v-chip>
            </template>
          </div>
        </div>
        
        <div class="chat-container" ref="chatContainer">
          <div class="messages-wrapper">
            <div v-for="(message, index) in messages" :key="index" class="message-container">
              <MessageBubble :message="message" />
            </div>
            <TypingIndicator v-if="isTyping && !currentAiMessage" />
          </div>
        </div>
        
        <div class="chat-input">
          <div class="input-wrapper">
            <div class="input-buttons">
              <v-btn
                variant="text"
                size="small"
                :color="isListening ? 'error' : 'primary'"
                class="voice-btn mr-2"
                @click="toggleVoiceInput"
                :class="{ 'pulse-animation': isListening }"
              >
                <v-icon>{{ isListening ? 'mdi-microphone' : 'mdi-microphone-outline' }}</v-icon>
              </v-btn>
              <v-btn
                icon="mdi-theme-light-dark"
                variant="text"
                size="small"
                @click="handleThemeToggle"
                class="theme-btn"
              />
            </div>
            <div class="input-content">
              <textarea
                ref="textareaRef"
                v-model="inputMessage"
                class="input-field"
                :disabled="isTyping"
                placeholder="输入你的问题..."
                @keydown="handleEnterPress"
                @input="adjustHeight"
                rows="1"
              ></textarea>
              <v-btn
                v-if="inputMessage"
                icon="mdi-send"
                variant="text"
                size="small"
                color="primary"
                class="send-btn"
                @click="handleSendClick"
              />
            </div>
          </div>
          
          <div class="input-tips text-caption text-grey mt-1">
            {{ isListening ? '正在听您说...' : '按 Enter 发送，Shift + Enter 换行' }}
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, nextTick, inject, onMounted, watch } from 'vue'
import MessageBubble from './MessageBubble.vue'
import TypingIndicator from './TypingIndicator.vue'
import { streamMessage, type ChatMessage } from '@/api/chat'

// 语音识别相关类型声明
interface SpeechRecognitionResult {
  readonly length: number;
  item(index: number): SpeechRecognitionAlternative;
  [index: number]: SpeechRecognitionAlternative;
  isFinal: boolean;
}

interface SpeechRecognitionAlternative {
  readonly transcript: string;
  readonly confidence: number;
}

interface SpeechRecognitionEvent {
  readonly resultIndex: number;
  readonly results: SpeechRecognitionResultList;
  readonly interpretation: any;
  readonly emma: Document | null;
}

interface SpeechRecognitionResultList {
  readonly length: number;
  item(index: number): SpeechRecognitionResult;
  [index: number]: SpeechRecognitionResult;
}

interface SpeechRecognitionErrorEvent extends Event {
  readonly error: string;
  readonly message: string;
}

interface SpeechRecognition extends EventTarget {
  continuous: boolean;
  grammars: any;
  interimResults: boolean;
  lang: string;
  maxAlternatives: number;
  onaudioend: ((this: SpeechRecognition, ev: Event) => any) | null;
  onaudiostart: ((this: SpeechRecognition, ev: Event) => any) | null;
  onend: ((this: SpeechRecognition, ev: Event) => any) | null;
  onerror: ((this: SpeechRecognition, ev: SpeechRecognitionErrorEvent) => any) | null;
  onnomatch: ((this: SpeechRecognition, ev: SpeechRecognitionEvent) => any) | null;
  onresult: ((this: SpeechRecognition, ev: SpeechRecognitionEvent) => any) | null;
  onsoundend: ((this: SpeechRecognition, ev: Event) => any) | null;
  onsoundstart: ((this: SpeechRecognition, ev: Event) => any) | null;
  onspeechend: ((this: SpeechRecognition, ev: Event) => any) | null;
  onspeechstart: ((this: SpeechRecognition, ev: Event) => any) | null;
  onstart: ((this: SpeechRecognition, ev: Event) => any) | null;
  start(): void;
  stop(): void;
  abort(): void;
}

declare global {
  interface Window {
    SpeechRecognition?: new () => SpeechRecognition;
    webkitSpeechRecognition?: new () => SpeechRecognition;
  }
}

// 消息类型
interface Message {
  text: string;
  isUser: boolean;
  timestamp: Date;
}

// 组件状态
const messages = ref<Message[]>([])
const inputMessage = ref('')
const isTyping = ref(false)
const chatContainer = ref<HTMLElement | null>(null)
const currentAiMessage = ref<Message | null>(null)
const isListening = ref(false)
let recognition: SpeechRecognition | null = null

// 快速提示语
const quickPrompts = [
  "你能做什么？",
  "写一个冒泡排序",
  "解释一下 Vue 3 的响应式原理",
  "帮我优化一段代码",
]

const useQuickPrompt = (prompt: string) => {
  inputMessage.value = prompt
  handleSendClick()
}

const scrollToBottom = async () => {
  await nextTick()
  if (chatContainer.value) {
    chatContainer.value.scrollTop = chatContainer.value.scrollHeight
  }
}

const initSpeechRecognition = () => {
  const SpeechRecognitionAPI = (window as any).SpeechRecognition || (window as any).webkitSpeechRecognition
  if (!SpeechRecognitionAPI) {
    return false
  }
  
  recognition = new SpeechRecognitionAPI()
  if (recognition) {
    recognition.lang = 'zh-CN'
    recognition.continuous = true
    recognition.interimResults = true
    
    let finalTranscript = ''
    
    recognition.onstart = () => {
      isListening.value = true
      finalTranscript = inputMessage.value
    }
    
    recognition.onend = () => {
      if (isListening.value && recognition) {
        recognition.start()
      }
    }
    
    recognition.onresult = (event: SpeechRecognitionEvent) => {
      let interimTranscript = ''
      
      for (let i = event.resultIndex; i < event.results.length; i++) {
        const transcript = event.results[i][0].transcript
        if ((event.results[i] as any).isFinal) {
          finalTranscript += transcript
        } else {
          interimTranscript += transcript
        }
      }
      
      inputMessage.value = finalTranscript + interimTranscript
    }
    
    recognition.onerror = (event: SpeechRecognitionErrorEvent) => {
      if (event.error === 'no-speech') {
        return
      }
      isListening.value = false
    }
  }
  
  return true
}

const toggleVoiceInput = () => {
  if (!recognition && !initSpeechRecognition()) {
    alert('您的浏览器不支持语音识别功能')
    return
  }
  
  if (isListening.value) {
    isListening.value = false
    recognition?.stop()
  } else {
    recognition?.start()
  }
}

const handleSendClick = async () => {
  if (inputMessage.value.trim()) {
    await handleSuggestionClick(inputMessage.value)
  }
}

// 注入主题切换函数
const toggleTheme = inject('toggleTheme') as () => void

// 处理主题切换
const handleThemeToggle = () => {
  if (toggleTheme) {
    toggleTheme()
  }
}

interface ChatHistoryItem {
  date: Date
  messages: Message[]
}

const showHistory = ref(false)
const chatHistory = ref<ChatHistoryItem[]>([])

// 格式化日期
const formatDate = (date: Date) => {
  return new Date(date).toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 新建对话
const newChat = () => {
  // 保存当前对话到历史记录
  if (messages.value.length > 0) {
    chatHistory.value.unshift({
      date: new Date(),
      messages: [...messages.value]
    })
    // 保存到 localStorage
    localStorage.setItem('chatHistory', JSON.stringify(chatHistory.value))
  }
  // 清空当前对话
  messages.value = []
}

// 加载历史对话
const loadChat = (chat: ChatHistoryItem) => {
  messages.value = [...chat.messages]
  showHistory.value = false
}

// 初始化时加载历史记录
onMounted(() => {
  const savedHistory = localStorage.getItem('chatHistory')
  if (savedHistory) {
    try {
      const parsed = JSON.parse(savedHistory)
      chatHistory.value = parsed.map((item: any) => ({
        ...item,
        date: new Date(item.date)
      }))
    } catch (e) {
      console.error('Failed to parse chat history:', e)
    }
  }
})

const textareaRef = ref<HTMLTextAreaElement | null>(null)

// 处理键盘事件
const handleEnterPress = async (e: KeyboardEvent) => {
  if (e.shiftKey) {
    return // Shift + Enter 换行
  }
  if (inputMessage.value.trim()) {
    await handleSendClick()
  }
}

// 调整文本框高度
const adjustHeight = () => {
  const textarea = textareaRef.value
  if (textarea) {
    textarea.style.height = 'auto'
    textarea.style.height = textarea.scrollHeight + 'px'
  }
}

// 监听输入框内容变化
watch(inputMessage, () => {
  nextTick(() => {
    adjustHeight()
  })
})

// 初始化时设置高度
onMounted(() => {
  adjustHeight()
})

const loadingSuggestions = ref(false)
const refreshingSuggestion = ref<number | null>(null)
const suggestions = ref([
  '🤖 你好！让我来帮你解决问题',
  '💡 需要编程帮助吗？',
  '📚 有什么想学习的知识？',
  '🎨 需要创意灵感吗？'
])
const chipColors = ['#9C27B0', '#2196F3', '#4CAF50', '#FF9800', '#E91E63', '#00BCD4']

// 生成问题建议的提示语
const generateTipPrompt = () => {
  return `请生成一个简短的、有趣的问题示例，这个问题应该能展示AI助手的能力。
  要求：
  1. 不超过30个字
  2. 要包含emoji表情
  3. 直接返回问题文本，不要包含其他内容
  4. 每次都要生成不同的问题
  5. 问题类型可以包括：编程开发、知识解答、数学计算、创意写作等
  6. 不要带引号或其他标点符号`
}

// 获取单个问题建议
const getTip = async () => {
  const messages: ChatMessage[] = [
    { role: 'user', content: generateTipPrompt() }
  ]
  
  let suggestion = ''
  try {
    for await (const chunk of streamMessage(messages)) {
      suggestion += chunk
    }
    return suggestion.trim()
  } catch (error) {
    console.error('获取建议失败:', error)
    return '🤖 让我来帮你解决问题吧'
  }
}

// 获取所有问题建议
const getSuggestions = async () => {
  loadingSuggestions.value = true
  suggestions.value = []
  
  try {
    // 并行获取所有建议
    const promises = Array(4).fill(null).map(() => getTip())
    const results = await Promise.all(promises)
    
    // 过滤掉重复的建议
    const uniqueSuggestions = [...new Set(results)]
    
    // 如果有重复导致数量不足，补充获取
    while (uniqueSuggestions.length < 4) {
      const newTip = await getTip()
      if (!uniqueSuggestions.includes(newTip)) {
        uniqueSuggestions.push(newTip)
      }
    }
    
    suggestions.value = uniqueSuggestions
  } catch (error) {
    console.error('获取建议失败:', error)
  } finally {
    loadingSuggestions.value = false
  }
}

// 刷新单个建议
const refreshSuggestion = async (index: number) => {
  refreshingSuggestion.value = index
  try {
    const newSuggestion = await getTip()
    suggestions.value[index] = newSuggestion
  } finally {
    refreshingSuggestion.value = null
  }
}

// 组件加载时获取建议
onMounted(async () => {
  await getSuggestions()
})

// 处理建议点击
const handleSuggestionClick = async (text: string) => {
  messages.value.push({
    text,
    isUser: true,
    timestamp: new Date()
  })
  await handleUserMessage(text)
}

// 处理用户消息
const handleUserMessage = async (text: string) => {
  isTyping.value = true
  
  try {
    const aiMessages: ChatMessage[] = messages.value.map(msg => ({
      role: msg.isUser ? 'user' : 'assistant',
      content: msg.text
    }))
    
    aiMessages.push({ role: 'user', content: text })
    
    let aiResponse = ''
    for await (const chunk of streamMessage(aiMessages)) {
      aiResponse += chunk
    }
    
    messages.value.push({
      text: aiResponse,
      isUser: false,
      timestamp: new Date()
    })
  } catch (error) {
    console.error('获取AI回复失败:', error)
    messages.value.push({
      text: '抱歉，我遇到了一些问题，请稍后再试。',
      isUser: false,
      timestamp: new Date()
    })
  } finally {
    isTyping.value = false
    inputMessage.value = ''
  }
}
</script>

<style scoped>
.chat-layout {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background: #ffffff;
  overflow: hidden;
}

.chat-main {
  flex: 1;
  display: flex;
  flex-direction: column;
  min-width: 0;
  position: relative;
  overflow: hidden;
}

.chat-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
  background: white;
  border-bottom: 1px solid #e2e8f0;
}

.header-left {
  display: flex;
  align-items: center;
}

.header-left .title {
  font-size: 16px;
  font-weight: 600;
  color: #1a202c;
}

.header-right {
  display: flex;
  align-items: center;
}

.chat-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  background: #ffffff;
  position: relative;
  overflow: hidden;
}

.welcome-message {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  text-align: center;
  width: 100%;
  max-width: 600px;
  padding: 0 20px;
  z-index: 5;
}

.welcome-message h2 {
  font-size: 24px;
  font-weight: 600;
  color: #1a202c;
}

.welcome-message p {
  color: #4a5568;
  font-size: 16px;
}

.quick-starts {
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
  gap: 8px;
}

.chat-container {
  flex: 1;
  overflow-y: auto;
  scroll-behavior: smooth;
  padding: 20px 0 120px;
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
}

.messages-wrapper {
  padding: 0 max(240px, 20%);
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.chat-input {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 20px max(240px, 20%) 24px;
  background: linear-gradient(to bottom, rgba(255, 255, 255, 0.5), rgba(255, 255, 255, 0.8));
  backdrop-filter: blur(10px);
  border-top: 1px solid rgba(226, 232, 240, 0.5);
  z-index: 100;
}

.input-wrapper {
  position: relative;
  background: rgba(255, 255, 255, 0.8);
  border: 1px solid rgba(99, 102, 241, 0.1);
  border-radius: 12px;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  backdrop-filter: blur(10px);
}

.input-buttons {
  display: flex;
  align-items: center;
  padding: 8px 16px;
  border-bottom: 1px solid rgba(99, 102, 241, 0.08);
}

.input-content {
  display: flex;
  align-items: flex-start;
  padding: 12px 16px;
}

.input-field {
  flex: 1;
  border: none;
  outline: none;
  background: transparent;
  font-size: 14px;
  line-height: 1.6;
  min-height: 24px;
  resize: none;
  padding: 0;
  margin: 0;
  width: 100%;
  font-family: inherit;
  color: #1a202c;
}

.input-field::placeholder {
  color: rgba(0, 0, 0, 0.4);
}

.send-btn {
  margin-left: 12px;
  margin-top: 2px;
  opacity: 0.8;
  transition: all 0.2s ease;
}

.send-btn:hover {
  opacity: 1;
  transform: scale(1.05);
}

.input-tips {
  text-align: right;
  padding-right: 12px;
  font-size: 12px;
  color: #6b7280;
  margin-top: 6px;
  opacity: 0.8;
}

:deep(.v-field) {
  border-radius: 16px;
  background: transparent !important;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}

:deep(.v-field__input) {
  padding: 14px 18px !important;
  font-size: 14px;
  min-height: unset !important;
  line-height: 1.5;
}

:deep(.v-field__outline) {
  border: none !important;
  opacity: 0 !important;
}

:deep(.v-field__prepend-inner) {
  margin-left: 0 !important;
  margin-right: 0 !important;
}

:deep(.v-field__append-inner) {
  padding-right: 14px;
}

:deep(.v-field__input .v-icon) {
  color: #6366f1;
  opacity: 0.7;
  transition: all 0.3s ease;
}

:deep(.v-field--focused .v-field__input .v-icon) {
  color: #6366f1;
  opacity: 1;
  transform: scale(1.05);
}

.chat-container::-webkit-scrollbar {
  width: 4px;
}

.chat-container::-webkit-scrollbar-track {
  background: transparent;
}

.chat-container::-webkit-scrollbar-thumb {
  background: #e2e8f0;
  border-radius: 4px;
}

.chat-container::-webkit-scrollbar-thumb:hover {
  background: #cbd5e1;
}

:deep(.v-theme--dark) {
  .chat-layout {
    background: #1a1b26;
  }
  
  .chat-main {
    background: #1a1b26;
  }
  
  .chat-content {
    background: #1a1b26;
  }
  
  .welcome-message h2 {
    color: #ffffff;
  }
  
  .welcome-message p {
    color: rgba(255, 255, 255, 0.9);
  }
  
  .chat-input {
    background: #1a1b26;
    border-top: 1px solid rgba(45, 55, 72, 0.5);
    backdrop-filter: none;
  }
  
  .input-wrapper {
    background: rgba(26, 27, 38, 0.8);
    border-color: rgba(255, 255, 255, 0.1);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
  }
  
  .input-buttons {
    border-bottom-color: rgba(255, 255, 255, 0.1);
  }
  
  .input-field {
    color: rgba(255, 255, 255, 0.9);
  }
  
  .input-field::placeholder {
    color: rgba(255, 255, 255, 0.3);
  }
  
  .input-tips {
    color: rgba(255, 255, 255, 0.5);
  }
  
  .chat-container::-webkit-scrollbar-thumb {
    background: #2d3748;
  }
  
  .chat-container::-webkit-scrollbar-thumb:hover {
    background: #4a5568;
  }
  
  .v-input__prepend {
    color: #9d7aee !important;
  }
  
  .v-input__prepend:hover {
    color: #b79ef6 !important;
  }
  
  :deep(.v-btn) {
    color: rgba(255, 255, 255, 0.9) !important;
  }
  
  :deep(.v-btn:hover) {
    color: #b79ef6 !important;
  }
}

@keyframes pulse {
  0% {
    transform: scale(1);
    opacity: 1;
  }
  50% {
    transform: scale(1.1);
    opacity: 0.8;
  }
  100% {
    transform: scale(1);
    opacity: 1;
  }
}

.pulse-animation {
  animation: pulse 1.5s infinite;
}

.voice-btn {
  opacity: 0.8;
  transition: all 0.2s ease;
}

.voice-btn:hover {
  opacity: 1;
  transform: scale(1.05);
}

.theme-btn {
  opacity: 0.8;
  transition: all 0.2s ease;
}

.theme-btn:hover {
  opacity: 1;
  transform: scale(1.05);
}

.floating-sidebar {
  position: fixed;
  left: 20px;
  top: 50%;
  transform: translateY(-50%);
  display: flex;
  flex-direction: column;
  gap: 16px;
  z-index: 100;
  background: rgba(255, 255, 255, 0.1);
  backdrop-filter: blur(10px);
  padding: 16px 8px;
  border-radius: 16px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  border: 1px solid rgba(255, 255, 255, 0.1);
}

.sidebar-btn {
  transition: all 0.3s ease;
}

.sidebar-btn:hover {
  transform: scale(1.1);
}

:deep(.v-theme--dark) {
  .floating-sidebar {
    background: rgba(0, 0, 0, 0.2);
    border-color: rgba(255, 255, 255, 0.05);
  }
}

/* 响应式适配 */
@media (max-width: 768px) {
  .floating-sidebar {
    left: 10px;
    padding: 12px 6px;
  }
}

/* 历史记录弹出层样式 */
.history-dialog {
  background: var(--v-background);
}

.history-toolbar {
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
}

.history-title {
  display: flex;
  align-items: center;
  font-size: 1.2rem;
  font-weight: 500;
}

.history-count {
  font-size: 0.9rem;
  opacity: 0.8;
}

.history-content {
  padding: 24px 0;
  height: calc(100vh - 64px);
  overflow-y: auto;
}

.history-list {
  padding: 0 16px;
}

.history-item {
  cursor: pointer;
  transition: all 0.3s ease;
  border: 1px solid rgba(var(--v-theme-primary), 0.1);
  background: rgba(var(--v-theme-surface), 0.8);
}

.history-item:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.1);
  border-color: rgba(var(--v-theme-primary), 0.3);
}

.history-item-content {
  padding: 16px;
}

.history-item-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.history-item-date {
  display: flex;
  align-items: center;
  color: rgba(var(--v-theme-on-surface), 0.7);
  font-size: 0.9rem;
}

.history-item-count {
  font-size: 0.8rem;
}

.history-item-preview {
  color: rgba(var(--v-theme-on-surface), 0.9);
  font-size: 0.95rem;
  line-height: 1.5;
  margin-bottom: 12px;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.history-item-footer {
  display: flex;
  justify-content: flex-end;
}

.history-item-btn {
  opacity: 0.8;
  transition: all 0.2s ease;
}

.history-item-btn:hover {
  opacity: 1;
  background: rgba(var(--v-theme-primary), 0.1);
}

/* 深色模式适配 */
:deep(.v-theme--dark) {
  .history-dialog {
    background: var(--v-theme-background);
  }

  .history-item {
    background: rgba(255, 255, 255, 0.05);
    border-color: rgba(255, 255, 255, 0.1);
  }

  .history-item:hover {
    border-color: rgba(255, 255, 255, 0.2);
    box-shadow: 0 6px 16px rgba(0, 0, 0, 0.2);
  }

  .history-item-date {
    color: rgba(255, 255, 255, 0.7);
  }

  .history-item-preview {
    color: rgba(255, 255, 255, 0.9);
  }
}

/* 响应式适配 */
@media (max-width: 768px) {
  .history-content {
    padding: 16px 0;
  }

  .history-list {
    padding: 0 12px;
  }

  .history-item-content {
    padding: 12px;
  }
}

:deep(.v-textarea textarea) {
  line-height: 1.5 !important;
  padding: 0 !important;
  min-height: 24px !important;
}

:deep(.v-field--focused) {
  box-shadow: none !important;
}

/* 输入框焦点状态 */
.input-wrapper:focus-within {
  border-color: rgba(99, 102, 241, 0.4);
  box-shadow: 0 4px 16px rgba(99, 102, 241, 0.1);
}

:deep(.v-theme--dark) .input-wrapper:focus-within {
  border-color: rgba(124, 58, 237, 0.4);
  box-shadow: 0 4px 16px rgba(124, 58, 237, 0.1);
}

.suggestions {
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
  gap: 0.8rem;
  min-height: 40px;
  align-items: center;
  margin-top: 1rem;
}

.suggestion-chip {
  transition: all 0.3s ease !important;
  font-weight: 500 !important;
  cursor: pointer !important;
}

.suggestion-chip:hover {
  transform: translateY(-2px);
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}

.suggestion-chip :deep(.v-chip__append) {
  opacity: 0;
  transition: opacity 0.3s ease;
}

.suggestion-chip:hover :deep(.v-chip__append) {
  opacity: 1;
}

/* 深色模式适配 */
:deep(.v-theme--dark) {
  .suggestion-chip:hover {
    box-shadow: 0 2px 8px rgba(255,255,255,0.1);
  }
}
</style>